﻿using MediatR;
using SystemWFH.API.Application.Command.ReviewCommand;
using SystemWFH.API.DTO;
using SystemWFH.Domain;
using SystemWFH.Infrstructer.Impl;
using SystemWFH.Infrstructer.Interface;

namespace SystemWFH.API.Application.CommandHandlers.ReviewCommandHandler
{
    public class ReviewGetAllCommandHandler : IRequestHandler<ReviewGetAllCommand, PageDTO<Review>>
    {
        private readonly IReviewRepository repository;
        public ReviewGetAllCommandHandler(IReviewRepository repository)
        {
            this.repository = repository;
        }
        public async Task<PageDTO<Review>> Handle(ReviewGetAllCommand request, CancellationToken cancellationToken)
        {
            PageDTO<Review> page = new PageDTO<Review>();
            var list = await repository.GetAllAsync();
            list = list.Where(x => x.IsDelete == false).ToList();
            if (!string.IsNullOrEmpty(request.reviewNo))
            {
                list = list.Where(x => x.reviewNo.Contains(request.reviewNo)).ToList();
            }
            if (!string.IsNullOrEmpty(request.reviewName))
            {
                list = list.Where(x => x.reviewName.Contains(request.reviewName)).ToList();
            }
            if (request.reviewState > 0)
            {
                list = list.Where(x => x.reviewState == request.reviewState).ToList();
            }
            page.listCount = list.Count;
            page.pageCount = (int)Math.Ceiling(page.listCount * 1.0 / request.pageSize);
            page.pageList = list.OrderByDescending(x => x.reviewId).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();

            return page;
        }
    }
}
